package cn.lili.modules.search.serviceimpl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.SearchPage;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.json.JSONUtil;
import cn.lili.common.vo.PageVO;
import cn.lili.modules.goods.entity.dos.Goods;
import cn.lili.modules.goods.entity.dos.GoodsSku;
import cn.lili.modules.goods.entity.dto.GoodsParamsDTO;
import cn.lili.modules.goods.mapper.GoodsSkuMapper;
import cn.lili.modules.goods.service.GoodsService;
import cn.lili.modules.goods.service.GoodsSkuService;
import cn.lili.modules.promotion.service.PromotionService;
import cn.lili.modules.search.entity.dos.GoodsIndex;
import cn.lili.modules.search.entity.dos.GoodsRelatedInfo;
import cn.lili.modules.search.entity.dto.GoodsSearchDTO;
import cn.lili.modules.search.entity.dto.SelectorOptions;
import cn.lili.modules.search.service.GoodsSearchService;
import cn.lili.mybatis.util.PageUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * ES商品搜索业务层实现
 *
 * @author paulG
 * @since 2020/10/16
 **/
@Slf4j
@Service
public class DbGoodsSearchServiceImpl implements GoodsSearchService {
	
	@Autowired
	private GoodsService goodService;
	@Autowired
	private GoodsSkuService goodSkuService;
	
	@Autowired
    protected GoodsSkuMapper goodsSkuMapper;
	
	@Autowired
    private PromotionService promotionService;
	
    private static final String ATTR_NAME_KEY = "nameList";
    private static final String ATTR_VALUE_KEY = "valueList";
	
	@Override
	public SearchPage<GoodsIndex> searchGoods(GoodsSearchDTO searchDTO, PageVO pageVo) {
		return null; // TODO 目前只有ES全量同步促销信息时会用到此接口，可以先不处理
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public Page<GoodsIndex> searchGoodsByPage(GoodsSearchDTO goodsSearch, PageVO pageVo) {
		QueryWrapper<GoodsSku> queryWrapper = this.toQueryWarpper(goodsSearch);
		
		Page<?> page = goodSkuService.page(PageUtil.initPage(pageVo), queryWrapper);
		List<GoodsSku> records = (List<GoodsSku>) page.getRecords();
		List goodsIndexs = new ArrayList(records.size());
		for(GoodsSku sku : records) {
			goodsIndexs.add(new GoodsIndex(sku));
		}
		page.setRecords(goodsIndexs);
		
		return (Page<GoodsIndex>) page;
	}

	@Override
	public GoodsRelatedInfo getSelector(GoodsSearchDTO goodsSearch) {
		//此函数返回搜索的所有商品的类目集合，品牌集合，参数集合（参数搜索目前不支持，所以不支持搜索功能）
		QueryWrapper<GoodsSku> queryWrapper = this.toQueryWarpper(goodsSearch);
		
		List<SelectorOptions> aggBrand = goodsSkuMapper.aggBrand(queryWrapper);
		GoodsRelatedInfo goodsRelatedInfo = new GoodsRelatedInfo();
		goodsRelatedInfo.setBrands(aggBrand);
		goodsRelatedInfo.setCategories(Collections.EMPTY_LIST);
		goodsRelatedInfo.setParamOptions(Collections.EMPTY_LIST);
		
		return goodsRelatedInfo; // TODO 用sql去查！摸清楚其逻辑，看是否必要
	}
	private QueryWrapper<GoodsSku> toQueryWarpper(GoodsSearchDTO goodsSearch){
		QueryWrapper<GoodsSku> queryWrapper = goodsSearch.queryWrapper();
		
		String curSkuId = goodsSearch.getCurrentGoodsSkuId();
		if (CharSequenceUtil.isNotBlank(curSkuId)) {
            queryWrapper.ne("id", queryWrapper);
            
            GoodsSku goodSkuCurr = goodSkuService.getGoodsSkuByIdFromCache(curSkuId);
            //推荐与当前浏览商品相同一个二级分类下的商品
            String categoryPath = goodSkuCurr.getCategoryPath();
            if (CharSequenceUtil.isNotBlank(categoryPath)) {
                //匹配二级分类
                String substring = categoryPath.substring(0, categoryPath.lastIndexOf(","));
                queryWrapper.likeRight("category_path", substring);
            }
        }
		
		return queryWrapper;
	}
	
	/**
     * 转换搜索结果为聚合商品展示信息
     *
     * @param aggregationMap 搜索结果
     * @return 聚合商品展示信息
     */
    private GoodsRelatedInfo convertToGoodsRelatedInfo(Map<String, Aggregation> aggregationMap, GoodsSearchDTO goodsSearch) {
    	return null;
//        GoodsRelatedInfo GoodsRelatedInfo = new GoodsRelatedInfo();
//        //分类
//        List<SelectorOptions> categoryOptions = new ArrayList<>();
//        ParsedStringTerms categoryTerms = (ParsedStringTerms) aggregationMap.get("categoryAgg");
//        List<? extends Terms.Bucket> categoryBuckets = categoryTerms.getBuckets();
//        if (categoryBuckets != null && !categoryBuckets.isEmpty()) {
//            categoryOptions = this.convertCategoryOptions(categoryBuckets);
//        }
//        GoodsRelatedInfo.setCategories(categoryOptions);
//
//        //品牌
//        ParsedStringTerms brandNameTerms = (ParsedStringTerms) aggregationMap.get("brandIdNameAgg");
//        ParsedStringTerms brandUrlTerms = (ParsedStringTerms) aggregationMap.get("brandIdUrlAgg");
//        List<? extends Terms.Bucket> brandBuckets = brandNameTerms.getBuckets();
//        List<? extends Terms.Bucket> brandUrlBuckets = brandUrlTerms.getBuckets();
//        List<SelectorOptions> brandOptions = new ArrayList<>();
//        if (brandBuckets != null && !brandBuckets.isEmpty()) {
//            brandOptions = this.convertBrandOptions(goodsSearch, brandBuckets, brandUrlBuckets);
//        }
//        GoodsRelatedInfo.setBrands(brandOptions);
//
//        //参数
//        ParsedNested attrTerms = (ParsedNested) aggregationMap.get("attrAgg");
//        if (!goodsSearch.getNotShowCol().isEmpty()) {
//            if (goodsSearch.getNotShowCol().containsKey(ATTR_NAME_KEY) && goodsSearch.getNotShowCol().containsKey(ATTR_VALUE_KEY)) {
//                GoodsRelatedInfo.setParamOptions(buildGoodsParam(attrTerms, goodsSearch.getNotShowCol().get(ATTR_NAME_KEY)));
//            }
//        } else {
//            GoodsRelatedInfo.setParamOptions(buildGoodsParam(attrTerms, null));
//        }
//
//        return GoodsRelatedInfo;
    }
	

	@Override
	public List<GoodsIndex> getGoodsBySkuIds(List<String> skuIds, PageVO pageVo) {
		List<GoodsSku> goodsSkuList = goodSkuService.getGoodsSkuByIdFromCache(skuIds);
		
		List<GoodsIndex> goodsIndexList = new ArrayList<GoodsIndex>(goodsSkuList.size());
		for(GoodsSku sku: goodsSkuList) {
			goodsIndexList.add(new GoodsIndex(sku));
		}
		
		return goodsIndexList;
	}

	@Override
	public GoodsIndex getGoodsBySkuId(String skuId) {
		GoodsSku goodsSku = goodSkuService.getGoodsSkuByIdFromCache(skuId);
		Goods goods = goodService.getById(goodsSku.getGoodsId());
		
		List<GoodsParamsDTO> list = null;
		if (CharSequenceUtil.isNotEmpty(goods.getParams())) {
            list = JSONUtil.toList(goods.getParams(), GoodsParamsDTO.class);
        } //参数可选 TODO

		GoodsIndex index = new GoodsIndex(goodsSku, list);
		
        Map<String, Object> goodsCurrentPromotionMap = promotionService.getGoodsSkuPromotionMap(index.getStoreId(), index.getId());
        //写入促销信息
        index.setPromotionMapJson(JSONUtil.toJsonStr(goodsCurrentPromotionMap));
        // 促销信息可选 TODO
        
		return index;
	}
	
}
